package client;
import java.util.Properties;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
public class MailMessage {
	
	private static final Properties properties = getConnectioDetails();
	private static final Session session = getConnection();
	
	/**
	 * Sends an email 
	 *
	 * @param recipient recipient of mail
	 * @param subject subject of the mail
	 * @param body body of the mail
	 */	
	public synchronized void sendMail(String recipient, String subject, String body)
	{	
		try 
		{	 
			Message message = new MimeMessage(session);
			message.setFrom(new InternetAddress("sgisystems11@gmail.com"));
			message.setRecipients(Message.RecipientType.TO,
					InternetAddress.parse(recipient));
			message.setSubject(subject);
			message.setText(body);
 
			Transport.send(message);
		}
		catch (MessagingException e) 
		{
			throw new RuntimeException(e);
		}	
		
	}	
	
	private static synchronized Session getConnection()
	{
		if(session!=null)
			return session;
		
		Session s = Session.getDefaultInstance(properties,new javax.mail.Authenticator()
				{	
					protected PasswordAuthentication getPasswordAuthentication()
					{
						return new PasswordAuthentication("sgisystems11","sgisystems1234");
					}});
		
		return s;
	}
	public static synchronized Properties getConnectioDetails()
	{
		if(properties!=null)
			return properties;
		
		Properties 	p = new Properties();
		p.put("mail.smtp.host", "smtp.gmail.com");
		p.put("mail.smtp.socketFactory.port", "465");
		p.put("mail.smtp.socketFactory.class","javax.net.ssl.SSLSocketFactory");
		p.put("mail.smtp.auth", "true");
		p.put("mail.smtp.port", "465");
		return p;
	}

}
